<template>
    <div class="notice-management">
      <div class="header">
        <h2>公告管理</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          发布公告
        </el-button>
      </div>
  
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="公告标题">
            <el-input
              v-model="searchForm.title"
              placeholder="请输入公告标题"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="公告类型">
            <el-select
              v-model="searchForm.type"
              placeholder="请选择类型"
              clearable
              style="width: 200px"
            >
              <el-option label="通知" :value="1" />
              <el-option label="公告" :value="2" />
              <el-option label="提醒" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 200px"
            >
              <el-option label="已发布" :value="1" />
              <el-option label="草稿" :value="2" />
              <el-option label="已撤回" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
  
      <!-- 表格区域 -->
      <div class="table-container">
        <el-table
          :data="tableData"
          v-loading="loading"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="title" label="公告标题" min-width="200" show-overflow-tooltip />
          <el-table-column prop="typeName" label="类型" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)">{{ row.typeName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="statusName" label="状态" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">{{ row.statusName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="publisherName" label="发布人" width="100" />
          <el-table-column prop="publishTime" label="发布时间" width="160">
            <template #default="{ row }">
              {{ row.publishTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="生效时间" width="160" />
          <el-table-column prop="endTime" label="失效时间" width="160" />
          <el-table-column prop="viewCount" label="查看次数" width="90" align="center" />
          <el-table-column prop="createTime" label="创建时间" width="160" />
          <el-table-column label="操作" width="240" fixed="right" align="center">
            <template #default="{ row }">
              <div class="action-grid">
                <!-- 第一行 -->
                <div class="action-row">
                  <el-button size="small" @click="handleView(row)" class="action-btn">
                    查看
                  </el-button>
                  <el-button size="small" @click="handleEdit(row)" class="action-btn">
                    编辑
                  </el-button>
                </div>
                <!-- 第二行 -->
                <div class="action-row">
                  <el-button 
                    size="small" 
                    type="warning" 
                    @click="handleUpdateStatus(row)"
                    class="action-btn"
                  >
                    {{ getStatusButtonText(row.status) }}
                  </el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    @click="handleDelete(row)"
                    class="action-btn"
                    :loading="deleteLoading === row.id"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
  
      <!-- 新增/编辑对话框 -->
      <NoticeFormDialog
        v-model="dialogVisible"
        :form-data="currentNotice"
        :is-edit="isEdit"
        @success="handleDialogSuccess"
      />
  
      <!-- 查看详情对话框 -->
      <el-dialog
        v-model="viewDialogVisible"
        title="公告详情"
        width="800px"
        :before-close="handleViewDialogClose"
      >
        <div class="notice-detail" v-if="currentViewNotice.id">
          <div class="detail-header">
            <h3 class="detail-title">{{ currentViewNotice.title }}</h3>
            <div class="detail-meta">
              <span class="meta-item">
                <el-tag :type="getTypeTagType(currentViewNotice.type)">
                  {{ currentViewNotice.typeName }}
                </el-tag>
              </span>
              <span class="meta-item">
                <el-tag :type="getStatusTagType(currentViewNotice.status)">
                  {{ currentViewNotice.statusName }}
                </el-tag>
              </span>
              <span class="meta-item">发布人：{{ currentViewNotice.publisherName }}</span>
              <span class="meta-item">发布时间：{{ currentViewNotice.publishTime || '-' }}</span>
              <span class="meta-item">查看次数：{{ currentViewNotice.viewCount }}</span>
            </div>
            <div class="detail-time">
              <span>生效时间：{{ currentViewNotice.startTime }}</span>
              <span style="margin-left: 20px;">失效时间：{{ currentViewNotice.endTime }}</span>
            </div>
          </div>
          <div class="detail-content">
            <div class="content-label">公告内容：</div>
            <div class="content-text">{{ currentViewNotice.content }}</div>
          </div>
        </div>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleViewDialogClose">关闭</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 状态变更对话框 -->
      <el-dialog
        v-model="statusDialogVisible"
        :title="`${getStatusActionText(currentStatusNotice.status)}公告`"
        width="400px"
        :before-close="handleStatusDialogClose"
      >
        <div class="status-dialog-content">
          <p>确定要{{ getStatusActionText(currentStatusNotice.status) }}公告 <strong>"{{ currentStatusNotice.title }}"</strong> 吗？</p>
        </div>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleStatusDialogClose">取消</el-button>
            <el-button 
              type="primary"
              @click="handleStatusConfirm"
              :loading="statusLoading"
            >
              {{ statusLoading ? '提交中...' : '确定' }}
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Search, Refresh } from '@element-plus/icons-vue'
  import { noticeApi } from '@/api/notice'
  import NoticeFormDialog from './components/NoticeFormDialog.vue'
  
  // 响应式数据
  const loading = ref(false)
  const deleteLoading = ref(null)
  const statusLoading = ref(null)
  const dialogVisible = ref(false)
  const viewDialogVisible = ref(false)
  const statusDialogVisible = ref(false)
  const isEdit = ref(false)
  const currentNotice = ref({})
  const currentViewNotice = ref({})
  const currentStatusNotice = ref({})
  
  // 搜索表单
  const searchForm = reactive({
    title: '',
    type: null,
    status: null
  })
  
  // 分页数据
  const pagination = reactive({
    page: 1,
    size: 10,
    total: 0
  })
  
  // 表格数据
  const tableData = ref([])
  
  // 生命周期
  onMounted(() => {
    loadNoticeList()
  })
  
  // 加载公告列表
  const loadNoticeList = async () => {
    try {
      loading.value = true
      const params = {
        ...searchForm,
        page: pagination.page,
        size: pagination.size
      }
      
      const response = await noticeApi.getNoticeList(params)
      
      if (response && response.code === 1) {
        tableData.value = response.data.rows || response.data
        pagination.total = response.data.total
      } else {
        ElMessage.error(response?.msg || '获取公告列表失败')
        tableData.value = []
        pagination.total = 0
      }
    } catch (error) {
      ElMessage.error('网络错误，请稍后重试')
      tableData.value = []
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }
  
  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    loadNoticeList()
  }
  
  // 重置
  const handleReset = () => {
    Object.assign(searchForm, {
      title: '',
      type: null,
      status: null
    })
    pagination.page = 1
    loadNoticeList()
  }
  
  // 分页大小改变
  const handleSizeChange = (size) => {
    pagination.size = size
    pagination.page = 1
    loadNoticeList()
  }
  
  // 当前页改变
  const handleCurrentChange = (page) => {
    pagination.page = page
    loadNoticeList()
  }
  
  // 新增公告
  const handleAdd = () => {
    isEdit.value = false
    currentNotice.value = {
      title: '',
      content: '',
      type: 1,
      status: 2, // 默认草稿状态
      publisherName: '当前用户',
      startTime: '',
      endTime: ''
    }
    dialogVisible.value = true
  }
  
  // 查看公告详情
  const handleView = (row) => {
    currentViewNotice.value = { ...row }
    viewDialogVisible.value = true
  }
  
  // 编辑公告
  const handleEdit = (row) => {
    isEdit.value = true
    currentNotice.value = { ...row }
    dialogVisible.value = true
  }
  
  // 更新公告状态
  const handleUpdateStatus = (row) => {
    currentStatusNotice.value = { ...row }
    statusDialogVisible.value = true
  }
  
  // 状态变更确认
  const handleStatusConfirm = async () => {
    try {
      statusLoading.value = true
      
      // 状态流转逻辑：草稿->发布，发布->撤回，撤回->发布
      let newStatus
      if (currentStatusNotice.value.status === 2) { // 草稿 -> 发布
        newStatus = 1
      } else if (currentStatusNotice.value.status === 1) { // 发布 -> 撤回
        newStatus = 3
      } else { // 撤回 -> 发布
        newStatus = 1
      }
      
      const response = await noticeApi.updateNoticeStatus(currentStatusNotice.value.id, newStatus)
      
      if (response.code === 1) {
        ElMessage.success(`${getStatusActionText(currentStatusNotice.value.status)}公告成功`)
        handleStatusDialogClose()
        loadNoticeList()
      } else {
        ElMessage.error(response.msg || '操作失败')
      }
    } catch (error) {
      ElMessage.error('操作失败')
    } finally {
      statusLoading.value = false
    }
  }
  
  // 关闭状态变更对话框
  const handleStatusDialogClose = () => {
    statusDialogVisible.value = false
    setTimeout(() => {
      currentStatusNotice.value = {}
    }, 300)
  }
  
  // 关闭查看对话框
  const handleViewDialogClose = () => {
    viewDialogVisible.value = false
    setTimeout(() => {
      currentViewNotice.value = {}
    }, 300)
  }
  
  // 删除公告
  const handleDelete = async (row) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除公告 "${row.title}" 吗？此操作不可恢复！`,
        '警告',
        {
          type: 'warning',
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          confirmButtonClass: 'el-button--danger'
        }
      )
      
      deleteLoading.value = row.id
      
      const response = await noticeApi.deleteNotice(row.id)
      
      if (response.code === 1) {
        ElMessage.success('删除公告成功')
        // 如果删除的是当前页的最后一条数据，需要跳转到上一页
        if (tableData.value.length === 1 && pagination.page > 1) {
          pagination.page -= 1
        }
        loadNoticeList()
      } else {
        ElMessage.error(response.msg || '删除公告失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    } finally {
      deleteLoading.value = null
    }
  }
  
  // 对话框操作成功
  const handleDialogSuccess = () => {
    dialogVisible.value = false
    loadNoticeList()
  }
  
  // 获取类型标签样式
  const getTypeTagType = (type) => {
    const typeMap = {
      1: 'primary',   // 通知
      2: 'success',   // 公告
      3: 'warning'    // 提醒
    }
    return typeMap[type] || 'info'
  }
  
  // 获取状态标签样式
  const getStatusTagType = (status) => {
    const statusMap = {
      1: 'success',   // 已发布
      2: 'info',      // 草稿
      3: 'warning'    // 已撤回
    }
    return statusMap[status] || 'info'
  }
  
  // 获取状态按钮文本
  const getStatusButtonText = (status) => {
    const textMap = {
      1: '撤回',
      2: '发布',
      3: '重新发布'
    }
    return textMap[status] || '操作'
  }
  
  // 获取状态操作文本
  const getStatusActionText = (status) => {
    const actionMap = {
      1: '撤回',
      2: '发布',
      3: '重新发布'
    }
    return actionMap[status] || '操作'
  }
  </script>
  
  <style scoped>
  .notice-management {
    padding: 20px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
  }
  
  .search-container {
    margin-bottom: 20px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 4px;
  }
  
  .table-container {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  
  /* 操作栏网格布局 */
  .action-grid {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  
  .action-row {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;
  }
  
  .action-btn {
    flex: 1;
    min-width: 70px;
    max-width: 80px;
    font-size: 12px;
    padding: 6px 8px;
  }
  
  /* 公告详情样式 */
  .notice-detail {
    padding: 10px 0;
  }
  
  .detail-header {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
  }
  
  .detail-title {
    margin: 0 0 15px 0;
    font-size: 18px;
    color: #303133;
    line-height: 1.4;
  }
  
  .detail-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .meta-item {
    font-size: 14px;
    color: #606266;
  }
  
  .detail-time {
    font-size: 14px;
    color: #909399;
  }
  
  .detail-content {
    line-height: 1.6;
  }
  
  .content-label {
    font-weight: 600;
    margin-bottom: 10px;
    color: #303133;
  }
  
  .content-text {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 4px;
    white-space: pre-wrap;
    line-height: 1.8;
    color: #606266;
  }
  
  /* 状态变更对话框样式 */
  .status-dialog-content {
    padding: 10px 0;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 10px;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 0;
    margin-right: 10px;
  }
  </style>